package com.srmt.spring.autoconfigure;

import com.srmt.common.config.ApplicationConfig;
import com.srmt.common.ratelimit.RateLimiter;
import com.srmt.document.api.DocumentService;
import com.srmt.document.factory.DocumentServiceFactory;
import com.srmt.spring.properties.DocumentProperties;
import com.srmt.spring.service.SpringDocumentServiceWrapper;
import com.srmt.user.api.UserIdResolver;
import com.srmt.user.factory.UserIdResolverFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.Map;

/**
 * Document SDK Spring Boot 自动配置
 * 
 * @author SRMT Development Team
 * @since 2.0.0
 */
@Configuration
@ConditionalOnClass({DocumentService.class})
@ConditionalOnProperty(prefix = "document", name = "enabled", havingValue = "true", matchIfMissing = true)
@EnableConfigurationProperties(DocumentProperties.class)
public class DocumentAutoConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(DocumentAutoConfiguration.class);

    /**
     * 自定义限流器（可选）
     * 如果Spring容器中存在用户自定义的RateLimiter Bean，将自动注入
     */
    @Autowired(required = false)
    private RateLimiter customRateLimiter;

    /**
     * 创建 DocumentService Bean
     */
    @Bean
    @Primary
    @ConditionalOnMissingBean(DocumentService.class)
    public DocumentService documentService(DocumentProperties properties) {
        logger.info("创建 文档服务 bean with platform: {}", properties.getService().getPlatform());

        ApplicationConfig config = buildApplicationConfig(properties);
        DocumentService originalService = DocumentServiceFactory.create(config);

        // 包装原始服务，添加Spring特性
        return new SpringDocumentServiceWrapper(originalService);
    }
    
    /**
     * 创建 UserIdResolver Bean
     */
    @Bean
    @ConditionalOnMissingBean(UserIdResolver.class)
    public UserIdResolver userIdResolver(DocumentProperties properties) {
        logger.info("创建 用户IdResolver bean for platform: {}", properties.getService().getPlatform());
        
        ApplicationConfig config = buildApplicationConfig(properties);
        return UserIdResolverFactory.create(config);
    }
    
    /**
     * 将 Spring Boot 配置转换为 ApplicationConfig
     */
    private ApplicationConfig buildApplicationConfig(DocumentProperties properties) {
        ApplicationConfig config = new ApplicationConfig();
        
        // 设置服务配置
        ApplicationConfig.ServiceSettings serviceSettings = new ApplicationConfig.ServiceSettings();
        serviceSettings.setPlatform(properties.getService().getPlatform());
        serviceSettings.setTimeout(properties.getService().getTimeout());
        serviceSettings.setLogReqAtDebug(properties.getService().isLogReqAtDebug());
        
        // 设置缓存配置
        ApplicationConfig.ServiceSettings.CacheSettings cacheSettings = 
                new ApplicationConfig.ServiceSettings.CacheSettings();
        cacheSettings.setEnabled(properties.getService().getCache().isEnabled());
        cacheSettings.setSize(properties.getService().getCache().getSize());
        cacheSettings.setTtlMinutes(properties.getService().getCache().getTtlMinutes());
        serviceSettings.setCache(cacheSettings);
        
        config.setService(serviceSettings);
        
        // 设置平台特定配置（目前只支持飞书）
        String platform = properties.getService().getPlatform();
        Map<String, String> platformConfig = properties.getCurrentPlatformConfig();
        
        if ("feishu".equalsIgnoreCase(platform) && platformConfig != null) {
            ApplicationConfig.FeishuSettings feishuSettings = new ApplicationConfig.FeishuSettings();
            feishuSettings.setAppId(platformConfig.get("app-id"));
            feishuSettings.setAppSecret(platformConfig.get("app-secret"));
            feishuSettings.setBaseUrl(platformConfig.getOrDefault("base-url", "https://open.feishu.cn"));
            feishuSettings.setDefaultFolderToken(platformConfig.getOrDefault("default-folder-token", ""));
            config.setFeishu(feishuSettings);
        }
        // 未来可以添加其他平台的配置转换
        // else if ("dingtalk".equalsIgnoreCase(platform)) { ... }
        
        // 直接设置限流配置（无需转换）
        config.setRateLimit(properties.getRateLimit());

        // 如果存在自定义限流器，自动注入到配置中
        if (customRateLimiter != null) {
            logger.info("检测到自定义限流器 Bean: {}, 自动注入到配置中",
                       customRateLimiter.getClass().getSimpleName());
            config.getRateLimit().setCustomRateLimiter(customRateLimiter);
        }

        // 直接设置重试配置（无需转换）
        config.setRetry(properties.getRetry());

        // 验证配置
        config.validate();

        return config;
    }
}